package com.duoec.magichour.service.impl;

import com.duoec.magichour.dto.UserInfo;
import com.duoec.magichour.mapper.ArticleCollectionMapper;
import com.duoec.magichour.pojo.ArticleCollection;
import com.duoec.magichour.service.ArticleCollectionService;
import com.duoec.magichour.service.ArticleService;
import com.duoec.magichour.service.UserService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * Created by ycoe on 17/6/25.
 */
@Service
public class ArticleCollectionServiceImpl implements ArticleCollectionService {
    @Autowired
    private ArticleCollectionMapper articleCollectionMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @Override
    public Set<Long> getUserCollectionArticleSet(List<Long> articleIds, Long userId) {
        Set<Long> articleIdSet = Sets.newHashSet();
        if(userId == 0 || articleIds == null || articleIds.isEmpty()) {
            return articleIdSet;
        }
        List<ArticleCollection> articleCollections = articleCollectionMapper.getArticleCollectionList(articleIds, userId);
        if (articleCollections == null) {
            return articleIdSet;
        }
        articleCollections.forEach(articleCollection -> articleIdSet.add(articleCollection.getArticleId()));
        return articleIdSet;
    }

    @Override
    public boolean getUserCollectionArticle(long articleId, long userId) {
        ArticleCollection ac = articleCollectionMapper.selectByPrimaryKey(articleId + "_" + userId);
        return ac != null;
    }

    @Transactional
    @Override
    public String collect(UserInfo userInfo, long articleId, Long authorId) {
        String id = userInfo.getId() + "_" + articleId;
        if(articleCollectionMapper.exists(id)) {
            //已经收藏过
            return id;
        }
        ArticleCollection articleCollection = new ArticleCollection();
        articleCollection.setArticleId(articleId);
        articleCollection.setUserId(userInfo.getId());
        articleCollection.setId(id);
        articleCollectionMapper.insertSelective(articleCollection);

        //文章收藏数+1
        articleService.incArticleCollection(articleId);

        //用户收藏+1
        userService.incFavoriteArticle(userInfo.getId());

        //用户被收藏+1
        userService.incFollowArticle(authorId);

        return articleCollection.getId();
    }
}
